package com.example.sls.utils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import redis.clients.jedis.Jedis;

import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * 编者：蓝江富
 * 时间：2024/6/17 14:30
 * <br>生成验证码，以用户名为键，保存验证码到redis中
 */
public class VerifyCodeUtil {
  private static final int WIDTH=100;
  static final int HEIGHT=50;
  public static void function(HttpServletResponse response) {
    BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
            BufferedImage.TYPE_INT_RGB);
    // step2,获得画笔
    Graphics2D g = image.createGraphics();
    // step3,¸给画布填充一个随机的颜色
    SecureRandom r = new SecureRandom();
    try{
      r = SecureRandom.getInstance("SHA1PRNG");
    }catch(NoSuchAlgorithmException e){
      e.printStackTrace();
    }
    g.fillRect(0, 0, WIDTH, HEIGHT);
    // step4, 在画布上绘画
    g.setColor(new Color(0, 0, 0));
    String str = "0123456789abcdefhijkmnpqrstuvwxyz0123456789";
    String code = "";
    for (int i = 0; i < 4; i++) {
      g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
      int h = (int) (20 + 10 * r.nextDouble());
      g.setFont(new Font(null, h, h));
      String ch = String.valueOf(str.charAt(r.nextInt(str.length())));

      //增加验证码识别难度
      AffineTransform trans = new AffineTransform();
      double radians = Math.toRadians(Math.random() * 25.0D + 10.0D);
      int anchorx = 17 * i + 8;
      trans.rotate(radians, anchorx, 20.0D);

      float scaleSize = r.nextFloat() + 0.8F;
      if (scaleSize > 1.0F) {
        scaleSize = 1.0F;
      }
      trans.scale(scaleSize, scaleSize);
      g.setTransform(trans);

      g.drawString(ch, i * WIDTH / 5, h);

      code = code + ch;

    }
    //将验证码保存到redis中
    Jedis jedis=new Jedis("localhost",6379);
    jedis.setex(code, 60,code);
    jedis.close();
    // 禁止图像缓存。
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");
    try {
      OutputStream ops = response.getOutputStream();

      javax.imageio.ImageIO.write(image, "jpeg", ops);
    }catch (Exception e){
      e.printStackTrace();
    }
  }
}
